package gui;

import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import connection.Relay;
import connection.SimulatorConnectionIn;
import connection.SimulatorConnectionOut;

import data.InputFileReader;
import data.InputFileRecordHandler;
import data.InputFileRelay;

public class ControlPanel extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel lblAddress, lblPort;
	private JTextField txtAddress, txtPort;
	private JButton btnConnect, btnOpenFile;
	private FileDialog dialog;
	private InputFileReader reader;
	private InputFileRelay fileRelay;
	private Relay connRelay;
	private InputFileRecordHandler inputHandler;
	private Socket socket;
	
	public ControlPanel() {
		super();
		
		dialog = new FileDialog((Frame) this.getParent());
		fileRelay = new InputFileRelay();
		connRelay = new Relay();
		
		lblAddress = new JLabel("Address: ");
		lblPort = new JLabel("Port: ");
		txtAddress = new JTextField("127.0.0.1");
		txtPort = new JTextField("11145");
		btnConnect = new JButton("Connect");
		btnConnect.addActionListener(this);
		btnOpenFile = new JButton("Open File");
		btnOpenFile.addActionListener(this);
		
		add(lblAddress);
		add(txtAddress);
		add(lblPort);
		add(txtPort);
		add(btnConnect);
		add(btnOpenFile);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnConnect) {
			try {
				socket = new Socket(txtAddress.getText(), Integer.parseInt(txtPort.getText()));
				btnConnect.setEnabled(false);
				SimulatorConnectionIn connIn = new SimulatorConnectionIn(socket, connRelay);
				SimulatorConnectionOut connOut = new SimulatorConnectionOut(socket, connRelay);
				Thread connInThread = new Thread(connIn);
				Thread connOutThread = new Thread(connOut);
				connInThread.start();
				connOutThread.start();
			} 
			catch (NumberFormatException e1) {
				e1.printStackTrace();
			} 
			catch (UnknownHostException e1) {
				e1.printStackTrace();
			} 
			catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		else if (e.getSource() == btnOpenFile) {
			dialog.setVisible(true);
			System.out.println(dialog.getDirectory());
			System.out.println(dialog.getFile());
			reader = new InputFileReader(new File(dialog.getDirectory() + dialog.getFile()), fileRelay);
			inputHandler = new InputFileRecordHandler(fileRelay, connRelay);
			Thread readerThread = new Thread(reader);
			Thread handlerThread = new Thread(inputHandler);
			readerThread.start();
			handlerThread.start();
		}		
	}
}
